<?php

namespace app\course\logic\coupon;

use app\common\exception\LogicException;
use app\course\model\coupon\CouponUser as CouponUserModel;
use app\user\model\user\TicketCoupon;
use ArrayObject;

/**
 * 用户领取的卡券逻辑类
 * @method buildSql()
 */
class CouponUser extends CouponUserModel
{

    /**
     * 用户对应机构最优卡券 - 根据价格计算
     * Author   亓官雨树<lucky.max@foxmail.com>
     * Date 2020-04-29
     *
     * @param $totalPrice
     * @param $mhmId
     * @return ArrayObject [type]                                   [description]
     */
    public function getUserBestCouponByTotalPrice($totalPrice, $mhmId)
    {
        $mid = request()->mid;
        $has = $this->where('user_id', $mid)->where('mhm_id', $mhmId)->findOrEmpty();

        if ($has->isEmpty()) return new ArrayObject();

        $field = "__TABLE__.id,__TABLE__.coupon_type,__TABLE__.price,__TABLE__.discount";

        $map1   = $map2 = [
            ['__TABLE__.mhm_id', '=', $mhmId],
            ['__TABLE__.delete_time', '=', null],
            ['u.status', '=', 0],
            ['user_id', '=', $mid],
        ];
        $map1[] = ['use_stime', '<', time()];
        $map1[] = ['use_etime', '>', time()];
        $mapRaw = 'end_time >' . time() . ' OR end_time is null';
        // 最优打折卡
        $discountCoupon = app(Coupon::class)->join('coupon_user u', 'u.coupon_id=__TABLE__.id')->field($field)->where($map1)->where('coupon_type', 2)->order('__TABLE__.discount')->findOrEmpty();

        $ticketDiscount = app(TicketCoupon::class)->join('coupon_user u', 'u.ticket_id=__TABLE__.id')->field($field . ',u.ticket_id')->where($map2)->whereRaw($mapRaw)->where('coupon_type', 2)->order('__TABLE__.discount')->findOrEmpty();

        $discountD      = (float)$discountCoupon->discount ?: 10;
        $ticketD        = (float)$ticketDiscount->discount ?: 10;
        $discount       = min($discountD, $ticketD);
        $discountPrice  = $discount ? bcmul(bcdiv(bcsub(10, $discount, 2), 10, 3), $totalPrice, 2) : 0;
        $discountCoupon = $discount ? ($discountD <= $ticketD ? $discountCoupon : $ticketDiscount) : new ArrayObject();
        //
        $discountCoupon->price = $discountPrice;

        // 最优优惠券
        $coupon = app(Coupon::class)->join('coupon_user u', 'u.coupon_id=__TABLE__.id')->field($field.',__TABLE__.maxprice')->where($map1)->where('coupon_type', 1)->where('__TABLE__.maxprice', '<=', $totalPrice)->where('__TABLE__.price', '>=', $discountPrice)->order('__TABLE__.price DESC')->findOrEmpty();

        $ticketCoupon = app(TicketCoupon::class)->join('coupon_user u', 'u.ticket_id=__TABLE__.id')->field($field . ',__TABLE__.maxprice,u.ticket_id')->where($map2)->whereRaw($mapRaw)->where('coupon_type', 1)->where('__TABLE__.maxprice', '<=', $totalPrice)->where('__TABLE__.price', '>=', $discountPrice)->order('__TABLE__.price DESC')->findOrEmpty();

        // 不存在大于打折卡优惠时返回打折卡
        if ($coupon->isEmpty() && $ticketCoupon->isEmpty()) return $discountCoupon;
        // 存在时返回优惠券
        $couponPrice = (float)$coupon->price;
        $ticketPrice = (float)$ticketCoupon->price;
        $priceC      = max($couponPrice, $ticketPrice);
        return $priceC ? ($couponPrice >= $ticketPrice ? $coupon : $ticketCoupon) : new ArrayObject();

    }

    /**
     * 退还订单卡券
     * Author 亓官雨树<lucky.max@foxmail.com>
     * Date 2021-09-02
     *
     * @param integer $user_id [description]
     * @param array   $coupon_ids
     * @param bool    $ticket
     * @return void [type]             [description]
     */
    public function returnOrderCoupon($user_id = 0, $coupon_ids = [], $ticket = false)
    {
        // $data = $this->whereUserId($user_id)->whereIn('coupon_id', $coupon_ids)->update(['status' => 0]);
        $updateData     = ['status' => 0];
        $field          = $ticket ? 'ticket_id' : 'coupon_id';
        $whereCondition = [
            ['user_id', '=', $user_id],
            [$field, 'IN', $coupon_ids]
        ];

        $data = $this::update($updateData, $whereCondition);

        if ($data->isEmpty()) throw new LogicException("卡券退还出错");
    }

}
